<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/1/24
 * Time: 13:52
 */

namespace App\Services\SeminarTemplates;


use App\Adapters\SeminarAdapter;
use App\Repositories\SeminarTemplates\SeminarRepository;
use App\Repositories\SeminarTemplates\SeminarTemplateRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class SeminarService
 * @package App\Services
 */
class SeminarService
{
    /**
     * @var SeminarRepository
     */
    protected $seminarRepository;

    /**
     * @var SeminarTemplateRepository
     */
    protected $seminarTemplateRepository;

    /**
     * SeminarService constructor.
     * @param SeminarRepository $seminarRepository
     * @param SeminarTemplateRepository $seminarTemplateRepository
     */
    public function __construct(SeminarRepository $seminarRepository, SeminarTemplateRepository $seminarTemplateRepository)
    {
        $this->seminarRepository = $seminarRepository;
        $this->seminarTemplateRepository = $seminarTemplateRepository;
    }


    /**
     * 处理专题信息
     * @author Jerry
     * @param int $id
     * @param int $isShow
     * @return array
     */
    public function handle(int $id, int $isShow)
    {

        $seminarData = $this->seminarRepository->findSeminarById($id, $isShow);

        if (empty($seminarData)) {
            throw new NotFoundHttpException('专题已过期！');
        }

        $seminarTemplateData = $this->seminarTemplateRepository->findSeminarTemplateBySeminarId($seminarData->id);

        $templateData = $this->getTemplateData($seminarTemplateData);

        return $templateData;
    }

    /**
     * 循环处理模板数据
     * @author Jerry
     * @param array $templates
     * @return array
     */
    protected function getTemplateData(array $templates)
    {
        if (empty($templates)) {
            throw new NotFoundHttpException('获取专题模版数据失败');
        }

        $data = [];

        foreach ($templates as $key => $value) {
            $template = $this->stencil(1)->handle($value);

            if (empty($template)) {
                continue;
            }

            $data[] = $template;
        }

        return $data;
    }

    /**
     * 使用适配器创建该类型服务
     * @author Jerry
     * @param int $type
     * @return SeminarAdapter
     */
    protected function stencil(int $type)
    {
        return new SeminarAdapter($type);
    }
}